package initialize

import (
	"crmeb-common/config"
	"gorm.io/driver/mysql"
	_ "gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

var (
	MerDb *gorm.DB
)

func init() {
	MerDb = GormMysqlByConfig()
}

// GormMysqlByConfig 初始化Mysql数据库用过传入配置
func GormMysqlByConfig() *gorm.DB {

	dbConfig := config.GlobalConfig.DB
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Duration(dbConfig.SlowThreshold) * time.Second, // 慢 SQL 阈值
			LogLevel:      dbConfig.LogLevel,                                   // Log level
			Colorful:      false,                                               // 禁用彩色打印
		},
	)
	if db, err := gorm.Open(mysql.Open(dbConfig.Url), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   dbConfig.Prefix,        // 表前缀
			SingularTable: dbConfig.SingularTable, // 禁用表名复数
		},
		Logger: newLogger,
	}); err != nil {
		panic(err)
	} else {

		db.InstanceSet("gorm:table_options", "ENGINE=InnoDB")
		sqlDB, _ := db.DB()
		sqlDB.Ping()
		sqlDB.SetMaxIdleConns(dbConfig.MinIdle)
		sqlDB.SetMaxOpenConns(dbConfig.MaxActive)
		return db
	}
}
